package com.wurd.test.wx.utils;

import com.wurd.test.exception.WxException;
import com.wurd.test.wx.mp.aes.AesException;
import com.wurd.test.wx.mp.aes.WXBizMsgCrypt;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

public class EncryptUtils {

    private static String encodingAesKey = "***";
    private static String token = "***";
    private static String appId = "***";

    private static String xmlFormat_pattern = "<xml><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";

    public static String encrypt(String decMsg, String timeStamp, String nonce) throws WxException {
        try {
            WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
            String encMsg = pc.encryptMsg(decMsg, timeStamp, nonce);
            return encMsg;
        } catch (AesException e) {
            e.printStackTrace();
            throw new WxException("加密异常");
        } catch (Exception e) {
            e.printStackTrace();
            throw new WxException("加密异常");
        }
    }

    public static String decrypt(String encMsg, String msg_signature, String timestamp, String nonce) throws WxException {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(encMsg);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");

            String encrypt = nodelist1.item(0).getTextContent();
            String xmlFormat = xmlFormat_pattern;
            String fromXML = String.format(xmlFormat, encrypt);
            WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
            return pc.decryptMsg(msg_signature, timestamp, nonce, fromXML);
        } catch (AesException e) {
            e.printStackTrace();
            throw new WxException("解密异常");
        } catch (Exception e) {
            e.printStackTrace();
            throw new WxException("解密异常");
        }
    }

}
